import { useEffect, useRef } from "react";
import { Outlet, useLocation, useNavigate } from "react-router";
import request from "./api/request";
import { useDispatch } from "react-redux";
import { setUser } from "@/store/user";
import { setDict } from "@/store/dict";
import { getRedirectUrl } from "@/tools";
import { getUserInfo, getDictInfo } from "@/api";
import "./App.css";

console.log(import.meta.env.VITE_SSO_LOGIN_URL); // import.meta.env.DEV

const Layout = () => {
  const dispatch = useDispatch();
  useEffect(() => {
    // sso login flow
    const token = localStorage.getItem("token");
    if (token) return;

    if (window.location.search.indexOf("code") > -1) {
      const usp = new URLSearchParams(window.location.search);
      const code = usp.get("code");
      fetch(`${import.meta.env.VITE_SERVER_ADDRESS}/api/sso/token`, {
        method: "POST",
        headers: {
          "content-type": "application/json",
        },
        body: JSON.stringify({
          code,
        }),
      })
        .then((res) => res.json())
        .then((res) => {
          if (res.error) {
            console.log(res.error);
            return;
          } else {
            localStorage.setItem("token", res.token);
            window.location.replace(window.location.pathname);
          }
        })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {});
      return;
    }

    window.location.href = getRedirectUrl();
  });

  useEffect(() => {
    // get global user info
    getUserInfo().then((data) => {
      const action = setUser(data);
      dispatch(action);
    });
    getDictInfo().then((data) => {
      dispatch(setDict(data))
    })
  }, []);

  return (
    <div className="flex flex-col h-full">
      <div className="page flex-1 overflow-auto">
        <Outlet></Outlet>
      </div>
    </div>
  );
};

export default Layout;
